(function(){
  // 兼容 Typecho 默认后台编辑器（textarea#text）
  function $(sel, ctx){ return (ctx||document).querySelector(sel); }
  function createEl(tag, cls){ const el=document.createElement(tag); if(cls) el.className=cls; return el; }
  function escapeMd(text){ return (text||'').replace(/([\\`*_{}\[\]()#+\-.!])/g,'\\$1'); }
  function insertAtCursor(textarea, text){
    const start = textarea.selectionStart || 0;
    const end = textarea.selectionEnd || 0;
    const before = textarea.value.substring(0, start);
    const after = textarea.value.substring(end);
    textarea.value = before + text + after;
    const pos = start + text.length;
    textarea.selectionStart = textarea.selectionEnd = pos;
    textarea.focus();
  }

  function ensureToolbar(){
    const editor = $('#text');
    if(!editor) return;
    let bar = $('#hyp-toolbar');
    if(bar) return;
    bar = createEl('div', 'hyp-bar');
    bar.id = 'hyp-toolbar';
    const btn = createEl('button', 'hyp-btn');
    btn.type = 'button';
    btn.textContent = '上传到 HuanYingPan';

    const input = createEl('input');
    input.type = 'file';
    input.accept = 'image/*';
    input.style.display = 'none';

    btn.addEventListener('click', ()=> input.click());

    input.addEventListener('change', async ()=>{
      const file = input.files && input.files[0];
      if(!file) return;
      const cfg = window.__HYP_CFG__ || {};
      if(!cfg.apiUrl || !cfg.apiKey){
        alert('请在插件设置中填写 API 地址与 API Key');
        return;
      }
      btn.disabled = true; btn.textContent = '上传中...';
      try{
        const fd = new FormData();
        fd.append('file', file);
        fd.append('apikey', cfg.apiKey);
        fd.append('show', String(cfg.show === '1' ? 1 : 0));
        const res = await fetch(cfg.apiUrl, { method:'POST', headers:{ 'X-API-Key': cfg.apiKey }, body: fd });
        let data;
        const ct = res.headers.get('content-type') || '';
        if(ct.indexOf('application/json') >= 0){
          data = await res.json();
        } else {
          const text = await res.text();
          try { data = JSON.parse(text); } catch(_) { data = { code: -1, msg: '非JSON响应', raw: text, status: res.status }; }
        }
        if(!res.ok){
          alert('HTTP错误：' + res.status + '，' + (data && data.msg ? data.msg : '请检查接口地址或跨域设置'));
        } else if(data && data.code === 0){
          const name = escapeMd(file.name);
          const url = data.viewurl || data.downurl;
          if(url){
            insertAtCursor(editor, `\n\n![${name}](${url})\n\n`);
          } else {
            alert('上传成功但未返回可用链接');
          }
        } else {
          alert('上传失败：' + (data && data.msg ? data.msg : '未知错误'));
        }
      }catch(e){
        alert('网络或解析错误：' + String(e));
      } finally {
        btn.disabled = false; btn.textContent = '上传到 HuanYingPan'; input.value='';
      }
    });

    bar.appendChild(btn);
    bar.appendChild(input);
    // 将工具条插入到编辑器上方
    const target = editor.parentElement || editor;
    target.parentElement.insertBefore(bar, target);
  }

  // 样式（浅色/暗色自适应）
  const style = document.createElement('style');
  style.textContent = `
    :root{ --hyp-primary:#2563eb; --hyp-border:#e5e7eb; }
    @media (prefers-color-scheme: dark){ :root{ --hyp-primary:#60a5fa; --hyp-border:#1f2937; } }
    .hyp-bar{ display:flex; gap:8px; margin:8px 0; }
    .hyp-btn{ background:var(--hyp-primary); color:#fff; border:none; border-radius:8px; padding:8px 12px; cursor:pointer; }
    .hyp-btn:disabled{ opacity:.7; cursor:not-allowed; }
  `;
  document.head.appendChild(style);

  document.addEventListener('DOMContentLoaded', ensureToolbar);
})();